package cn.edu.ctbu.datajpa01.webapi;

import cn.edu.ctbu.datajpa01.core.PageUtils;
import cn.edu.ctbu.datajpa01.domain.Achievement;
import cn.edu.ctbu.datajpa01.service.AchievementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;



@RestController
@RequestMapping("/webapi/achievement")
public class AchievementRestController {

    @Autowired
    AchievementService achievementService;


    /**
     * 条件、分页查询
     * @param page
     * @param size
     * @param name
     * @return
     */
    @GetMapping("/getbypage")
    public PageUtils getByPage(@RequestParam(value = "page",defaultValue = "0") Integer page,
                               @RequestParam(value = "size",defaultValue = "10") Integer size,
                               @RequestParam(value = "name",defaultValue = "") String name) {
        Page<Achievement> achievementPage;
        //参数为空，正常查询
        if (StringUtils.isEmpty(name)) {
            Pageable pageable = PageRequest.of(page, size, Sort.by("id").descending());
            achievementPage = achievementService.findAll(pageable);

        }//匹配姓名查询
        else  {
            Achievement achievement=new Achievement();
            achievement.setName(name);
            Pageable pageable=  PageRequest.of(0,3, Sort.by("id").ascending());
            ExampleMatcher matcher=ExampleMatcher.matching()
                    .withMatcher("name",ExampleMatcher.GenericPropertyMatchers.contains());
            Example<Achievement> example=Example.of(achievement,matcher);
            achievementPage=achievementService.findAll(example,pageable);
        }


        PageUtils pageUtils=new PageUtils(achievementPage.getContent(), achievementPage.getTotalElements());
        return pageUtils;
    }


    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable  Integer id){

        achievementService.delete(id);

    }

    @GetMapping("/get/{id}")
    public Achievement get(@PathVariable Integer id){
        Achievement achievement=achievementService.getById(id);
        return achievement;
    }

    @PutMapping("/update")
    public Achievement update(Achievement achievement){
        //读取旧数据
        achievement = achievementService.update(achievement);
        return achievement;

    }

    @PostMapping("/insert")
    public Achievement insert(Achievement achievement){

        Achievement achievement1 = achievementService.insert(achievement);
        return achievement1;

    }

}
